const express = require("express");
const router = express.Router();
const companyMapper = require('../mapper/companyMapper');
const conn = require('../utils/conn');
const jwt = require('../utils/jwt');

router.post('/v1/company', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 0) {
    return;
  }
  const { id, cName, licenseId, bankId, content, capacity } = req.body;
  if(id != validate) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }

  conn.query(companyMapper.add, [ id, cName, licenseId, bankId, content, capacity ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.put('/v1/company', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 0) {
    return;
  }
  const { id, licenseId } = req.body;
  if(id != validate) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }

  conn.query(companyMapper.update, [ licenseId, Date.now(), id ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.get('/v1/company', (req, res) => {
  conn.query(companyMapper.select, [], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  }); 
});

module.exports = router;